package com.eascs.banknet.boc.service.trans;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.BOCS01Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.bocS01.BOCS01Bean;
import com.eascs.banknet.boc.vo.bocS01.BOCS01Element;
import com.eascs.banknet.boc.vo.bocS01.BOCS01Root;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

/**
 * 贷款额度测算
 * @author user
 *
 */
@Service("bocS01Service")
public class BOCS01Service extends BOCAbstractService {
	private static final Logger logger = LoggerFactory.getLogger(BOCS01Service.class);
	@Autowired
	private BOCS01Dao bocS01Dao;
	
	private String startId = "";
	
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("S01");
		logEntity.setTypeName("额度测算");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
	

	@Override
	public Map<String, String> dowork() {
		Map<String, String> result = new HashMap<>();
		String id = "";
		String loanapplyNo = "";
		LogEntity logEntity = initLogData();
		try {
			logger.info("额度测算调用开始，startId:[{}]", startId);
			/**
			 * 获取业务数据，组装xml消息
			 */
			BOCS01Root root = new BOCS01Root();
			BOCS01Element element = null;
			while(null == element){
				//查询需要申请贷款的数据
				BOCS01Bean data = bocS01Dao.queryData(startId);
				if(null == data){
					startId = null;
					logger.info("额度测算,没有符合条件的数据");
					return null;
				}
				id = data.getAPPNO();
				loanapplyNo = loanapplyDao.getLoanapplyNoByAppno(id);
				startId = id;
				//检查主门信息是否完整，否则记录日志并跳过
				if(!StringUtil.hasText(data.getVOCATION())){
					logger.error("客户主门店行业类别为空，id:[{}],customerId:[{}]！", id, data.getCustomerId());
					throw new Exception("客户主门店行业类别为空");
				}else{
					element = new BOCS01Element();
					BeanUtils.copyProperties(element, data);
				}
				BigDecimal revenue = new BigDecimal(element.getREVENUE());
				if(revenue.compareTo(BigDecimal.ZERO) == -1){
					element.setREVENUE("0");
				}
			}
			root.getBody().setElement(element);
			String xml = XmlHelp.convertToXml(root);
			XmlHelp.createXml("S01" + "(" + loanapplyNo + ")", loanapplyNo + "&" + XmlHelp.convertToXml(root), "BOCS01RQ", bocUtil.getEaFtpInfo());
			
			/*
			 * 调用中行接口
			 */	
			logger.info("组装XML请求完成，调用中行S01接口, id:{},xml:{}", id, xml);
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(), "S01", null, xml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行B01接口返回数据为空！");
				throw new Exception("中行S01接口返回数据为空");
			}
			logger.info("中行S01接口返回xml完成, returnXml：{}", returnXml);
			
			/**
			 * 保存返回信息
			 */
			XmlHelp.createXml("S01"+"("+id+")",returnXml,"BOCS01RS", bocUtil.getEaFtpInfo());
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			Element body = rsRoot.getChild("BODY");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				throw new Exception(head.getChildText("NOTE"));
			}
			Element trn = body.getChild("OUTPUT");
			Element creditcal = trn.getChild("CREDITCAL");
			String appno = creditcal.getChildText("APPNO");
			String creditline = creditcal.getChildText("CREDITLINE");
			String creditrange = creditcal.getChildText("CREDITRANGE");
			int rw = bocS01Dao.updateInfo(appno, creditline, creditrange);
			if(rw <= 0){
				throw new Exception("更新中行BOCS01接口结果失败");
			}
			logger.info("额度测算调用成功,appno:[{}]", appno);
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_SUCCESS, null);
		} catch (Exception e) {
			logger.error("额度测算出现异常，appno：[{}]，errMsg：[{}]", id,  e);
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
}
